package com.bys.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.bys.exception.BysOaSystemException;
import io.jsonwebtoken.*;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.*;
import java.util.Date;
import java.util.Optional;
import java.util.Random;

public class JwtUtil {
    public static final String key = "bys.com";

    private static PrivateKey getSecretKey() {
        PrivateKey privateKey = null;
        InputStream stream = JwtUtil.class.getClassLoader().getResourceAsStream("secret.rsa");
        try {
            ObjectInputStream ins = new ObjectInputStream(stream);
            privateKey = (PrivateKey) ins.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return privateKey;

    }

    /**
     * 生成 token
     */
    public static String createToken(Long userId, String username) {
        PrivateKey secretKey = getSecretKey();
        Optional.ofNullable(secretKey).orElseThrow(() -> new BysOaSystemException("密钥文件丢失"));
        // token 有效期 10 天
        Date date = DateUtil.offsetDay(new Date(), 10).toJdkDate();
        return Jwts.builder()
                .setSubject("auth-user") // 设置JWT的主题（subject）声明
                .setExpiration(date)
                .claim("userId", userId)
                .claim("username", username)
                .signWith(SignatureAlgorithm.RS256,secretKey )  //使用 RS256 算法进行数字签名
                .compressWith(CompressionCodecs.GZIP) // 压缩数据
                .compact();
    }

    public static Long getUserId(String token) {
        Long userId = null;
        if (StringUtils.isNotBlank(token)) {
            Claims claims = Jwts.parser().setSigningKey(getSecretKey()).parseClaimsJws(token).getBody();
            userId = claims.get("userId", Long.class);
        }
        return userId;
    }

    public static String getUsername(String token) {
        String username = null;
        if (StringUtils.isNotBlank(token)) {
            Claims claims = Jwts.parser().setSigningKey(getSecretKey()).parseClaimsJws(token).getBody();
            username = claims.get("username", String.class);
        }
        return username;

    }

}
